package com.sywb.chuangyebao.contract;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseIntArray;
import android.widget.TextView;

import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.InterestIndustryInfo;
import com.sywb.chuangyebao.utils.HttpCallback;
import com.sywb.chuangyebao.utils.HttpUtils;
import com.sywb.chuangyebao.view.MainAtlasActivity;
import com.sywb.chuangyebao.widget.GridSpacingItemDecoration;

import org.bining.footstone.adapter.BasePagerAdapter;
import org.bining.footstone.adapter.BaseRecyclerAdapter;
import org.bining.footstone.adapter.ViewHolderHelper;
import org.bining.footstone.adapter.listener.OnItemChildClickListener;
import org.bining.footstone.db.DbManager;
import org.bining.footstone.mvp.IView;
import org.bining.footstone.presenter.BasePresenter;
import org.bining.footstone.utils.ApkUtils;
import org.bining.footstone.utils.SharedUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public interface GuideContract {

    interface View extends IView {

        ViewPager getViewPager();

        TextView getButton();
    }

    class Presenter extends BasePresenter<GuideContract.View> {

        private ViewPager viewPager;

        private GuideStateAdapter adapter;
        private GuideTradeAdapter tradeAdapter;
        private SparseIntArray checkedTrades;

        @Override
        public void onStart() {
            viewPager = mView.getViewPager();
            btnNext = mView.getButton();
            //初始化ViewPager里的View
            List<android.view.View> viewList = new ArrayList<>();// 将要分页显示的View装入数组中
            viewList.add(initView(0));
            viewList.add(initView(1));
            viewPager.setAdapter(new BasePagerAdapter(viewList));
            viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    switch (position) {
                        case 0:
                            btnNext.setText(R.string.enter_next);
                            btnNext.setClickable(true);
                            btnNext.setEnabled(true);
                            break;
                        case 1:
                            changeButtonAfterCheck();
                            break;
                    }
                    currentIndex = position;
                }

                @Override
                public void onPageScrollStateChanged(int state) {
                }
            });
        }

        private android.view.View initView(int position) {
            android.view.View view0 = mActivity.getLayoutInflater().inflate(R.layout.layout_guide_page, null);
            TextView titleBig = view0.findViewById(R.id.guide_title_big);
            TextView titleSmall = view0.findViewById(R.id.guide_title_small);
            RecyclerView recyclerView = view0.findViewById(R.id.common_recycler);
            int column = 0;
            int spacing = 0;
            switch (position) {
                case 0:
                    titleBig.setText(R.string.select_state);
                    titleSmall.setText(R.string.update_change);
                    column = 2;
                    adapter = new GuideStateAdapter(mActivity);
                    int period = SharedUtils.getInt(Constants.USERBUSINESSPERIOD, 0);
                    adapter.setSelectedIndex(period);
                    adapter.setDatas(Arrays.asList(mActivity.getResources().getStringArray(R.array.guide_states)));
                    recyclerView.setAdapter(adapter);
                    spacing = mActivity.getResources().getDimensionPixelSize(R.dimen.dp_24);
                    break;
                case 1:
                    titleBig.setText(R.string.select_trade);
                    titleSmall.setText(R.string.update_change_trade);
                    column = 3;

                    tradeAdapter = new GuideTradeAdapter(mActivity);
                    checkedTrades = new SparseIntArray();

                    List<InterestIndustryInfo> list = DbManager.getInstance().query(InterestIndustryInfo.class);
                    if (list != null && list.size() > 0) {
                        tradeAdapter.setDatas(list);
                        for (InterestIndustryInfo i : list
                                ) {
                            if (i.isChecked) {
                                checkedTrades.put(i.categoryId, i.categoryId);
                            }
                        }
                    }

                    HttpUtils.listCategory(0, new HttpCallback<List<InterestIndustryInfo>>() {
                        @Override
                        public void onSuccess(List<InterestIndustryInfo> categories) {
                            if (mView != null && categories != null && categories.size() > 0) {
                                for (int i = 0; i < categories.size(); i++) {
                                    InterestIndustryInfo interestIndustryInfo = categories.get(i);
                                    interestIndustryInfo.sort = i;
                                    switch (interestIndustryInfo.name) {
                                        default:
                                        case "创业交流":
                                            interestIndustryInfo.face = R.drawable.commu_fill;
                                            break;
                                        case "餐饮美食":
                                            interestIndustryInfo.face = R.drawable.food_fill;
                                            break;
                                        case "服装鞋包":
                                            interestIndustryInfo.face = R.drawable.clothing;
                                            break;
                                        case "生活服务":
                                            interestIndustryInfo.face = R.drawable.service_filll;
                                            break;
                                        case "酒水饮料":
                                            interestIndustryInfo.face = R.drawable.drink_fill;
                                            break;
                                        case "家居用品":
                                            interestIndustryInfo.face = R.drawable.furnish_fill;
                                            break;
                                        case "美容保养":
                                            interestIndustryInfo.face = R.drawable.cosmet_fill;
                                            break;
                                        case "汽车服务":
                                            interestIndustryInfo.face = R.drawable.car_fill;
                                            break;
                                        case "建材装饰":
                                            interestIndustryInfo.face = R.drawable.material_fill;
                                            break;
                                        case "礼品饰品":
                                            interestIndustryInfo.face = R.drawable.gift_fill;
                                            break;
                                        case "环保机械":
                                            interestIndustryInfo.face = R.drawable.protection_fill;
                                            break;
                                        case "母婴用品":
                                            interestIndustryInfo.face = R.drawable.baby_fill;
                                            break;
                                        case "教育网络":
                                            interestIndustryInfo.face = R.drawable.education_fill;
                                            break;
                                    }

                                    InterestIndustryInfo localInfo = DbManager.getInstance().queryById(interestIndustryInfo.categoryId, InterestIndustryInfo.class);
                                    if (localInfo != null) {
                                        interestIndustryInfo.isChecked = localInfo.isChecked;
                                    } else {
                                        interestIndustryInfo.isChecked = false;
                                    }
                                }

                                DbManager.getInstance().deleteAll(InterestIndustryInfo.class);
                                DbManager.getInstance().save(categories);

                                tradeAdapter.setDatas(categories);
                            }
                        }

                        @Override
                        public void onError(String strMsg) {
                            super.onError(strMsg);
                            if (mView != null && tradeAdapter.getDataCount() == 0) {
                                showMessage(strMsg);
                            }
                        }
                    });

                    recyclerView.setAdapter(tradeAdapter);
                    spacing = mActivity.getResources().getDimensionPixelSize(R.dimen.dp_20);
                    break;
            }

            recyclerView.setLayoutManager(new GridLayoutManager(mActivity, column));
            GridSpacingItemDecoration recyclerDivider = new GridSpacingItemDecoration(spacing, false);
            recyclerView.addItemDecoration(recyclerDivider);
            return view0;
        }

        private int currentIndex; //0选择创业状态  1选择行业类型
        private TextView btnNext;

        public void clickNext() {
            switch (currentIndex) {
                case 0:
                    //当前为选择创业状态，执行点击进入下一页
                    SharedUtils.put(Constants.USERBUSINESSPERIOD, adapter.getSelectedIndex() + 1);
                    changeButtonAfterCheck();
                    currentIndex = 1;
                    mView.getViewPager().setCurrentItem(currentIndex);
                    break;
                case 1:
                    //当前为选择行业状态
                    SharedUtils.put(Constants.LASTUSEVERSION, ApkUtils.getVersionCode());
                    mView.advance(MainAtlasActivity.class);
                    break;
            }
        }

        class GuideStateAdapter extends BaseRecyclerAdapter<String> implements OnItemChildClickListener {

            private Integer[] stateImages = {R.drawable.g0_image01, R.drawable.g0_image02, R.drawable.g0_image03, R.drawable.g0_image04,};

            private int selectedIndex;

            GuideStateAdapter(Context context) {
                super(context, R.layout.item_guide_state);
            }

            @Override
            protected void setItemData(ViewHolderHelper viewHolderHelper, int i, String s) {
                viewHolderHelper.setOnItemChildClickListener(this);
                viewHolderHelper.setItemChildClickListener(R.id.ll_state);

                viewHolderHelper.setText(R.id.tv_state, s);
                viewHolderHelper.setImageResource(R.id.iv_state, stateImages[i]);
                viewHolderHelper.setImageResource(R.id.iv_check, i == selectedIndex ? R.drawable.check_icon02 : R.drawable.check_icon01);
            }

            @Override
            public void onItemChildClick(android.view.View view, int i) {
                if (i == selectedIndex) {
                    return;
                }
                selectedIndex = i;
                notifyDataSetChanged();
            }

            public void setSelectedIndex(int selectedIndex) {
                this.selectedIndex = selectedIndex;
            }

            public int getSelectedIndex() {
                return selectedIndex;
            }
        }

        class GuideTradeAdapter extends BaseRecyclerAdapter<InterestIndustryInfo> implements OnItemChildClickListener {

//            private int g1_iv[] = {R.drawable.commu_fill,
//                    R.drawable.drink_fill,
//                    R.drawable.education_fill,
//                    R.drawable.car_fill,
//                    R.drawable.protection_fill,
//                    R.drawable.material_fill,
//                    R.drawable.baby_fill,
//                    R.drawable.furnish_fill,
//                    R.drawable.gift_fill,
//                    R.drawable.cosmet_fill,
//                    R.drawable.service_filll,
//                    R.drawable.food_fill,
//                    R.drawable.clothing};

            GuideTradeAdapter(Context context) {
                super(context, R.layout.item_guide_trade);
            }

            @Override
            protected void setItemData(ViewHolderHelper viewHolderHelper, int i, InterestIndustryInfo model) {
                viewHolderHelper.setOnItemChildClickListener(this);
                viewHolderHelper.setItemChildClickListener(R.id.rl_guide_trade);

                viewHolderHelper.setImageResource(R.id.iv_trade_check, model.isChecked ? R.drawable.check_icon02 : R.drawable.check_icon01);
                try {
                    viewHolderHelper.setImageResource(R.id.iv_guide_trade, model.face);
                } catch (Exception e) {
                    viewHolderHelper.setImageResource(R.id.iv_guide_trade, R.drawable.image_def);
                }
                viewHolderHelper.setText(R.id.tv_guide_trade, model.name);
            }

            @Override
            public void onItemChildClick(android.view.View view, int i) {
                InterestIndustryInfo model = mDatas.get(i);
                if (model.isChecked) {
                    model.isChecked = false;
                    checkedTrades.delete(model.categoryId);
                } else {
                    model.isChecked = true;
                    checkedTrades.put(model.categoryId, model.categoryId);
//                    if (checkedTrades.size() < 5) {
//                        model.isChecked = true;
//                        checkedTrades.put(model.categoryId, model.categoryId);
//                    } else {
//                        showMessage("最多选择5个感兴趣的领域");
//                        return;
//                    }
                }

                DbManager.getInstance().update(model);

                notifyDataSetChanged();
                changeButtonAfterCheck();
            }
        }

        private void changeButtonAfterCheck() {
            if (checkedTrades.size() > 0) {
                btnNext.setText(R.string.open_go);
                btnNext.setClickable(true);
                btnNext.setEnabled(true);
            } else {
                btnNext.setText(R.string.select_one);
                btnNext.setClickable(false);
                btnNext.setEnabled(false);
            }
        }
    }
}

